//
//  DatabaseManager.swift
//  CatPomodoroTimer
//
//  Created by Xuri Li on 2024/8/28.
//

import Foundation
import SQLite

class DatabaseManager {
    
    static let shared = DatabaseManager()  // 单例实例
    
    private(set) var db: Connection?  // 数据库连接
    
    private init() {
        do {
            // 设置数据库文件路径，存储在应用的沙盒目录中
            let documentDirectory = try FileManager.default.url(
                for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true
            )
            let dbPath = documentDirectory.appendingPathComponent("cat_pomodoro_timer_database.sqlite3").path
            
            // 创建数据库连接
            db = try Connection(dbPath)
            
            // 初始化表（仅在第一次运行时创建表）
            if !isTableExists("FocusTasks") {
                try FocusTask.createTable(db: db!)
            }
        } catch {
            print("Error initializing database: \(error)")
        }
    }
    
    // 检测表是否存在
    private func isTableExists(_ tableName: String) -> Bool {
        do {
            let query = "SELECT name FROM sqlite_master WHERE type='table' AND name='\(tableName)'"
            for row in try db!.prepare(query) {
                if let name = row[0] as? String,
                   name == tableName {
                    return true
                }
            }
        } catch {
            print("Error checking if table exists: \(error)")
        }
        return false
    }
}
